import { NextApiResponse } from "next";
import { AuthenticatedRequest, withAuth } from "@common/middleware/auth";
import R from "@common/type/response";
import { SysPermissionService } from "@common/service/sys_permissions";
import { SysUserRoleDao } from "@common/dao/sys_user_role.dao";
import { getRoleById } from "@common/dao/sys_role.dao";

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    const loginUser = req.user;
    const user = loginUser?.user;
    
    if (!user) {
        return R.error(res, '用户信息不存在');
    }
    
    try {
        // 获取用户权限
        const permissions = await SysPermissionService.getUserPermissions(user.user_id);
        
        // 获取用户角色
        const userRoles = await SysUserRoleDao.getUserRoleIds(user.user_id);
        const roles = [];
        
        for (const userRole of userRoles) {
            const role = await getRoleById(userRole.role_id);
            if (role) {
                roles.push(role);
            }
        }
        
        let result = {
            user: user,
            roles: roles,
            permissions: permissions
        }
        
        R.success(res, result);
    } catch (error) {
        console.error('获取用户信息失败:', error);
        R.error(res, '获取用户信息失败');
    }
}

export default withAuth(handler);